import style from './render/style'
import Layout from './engine'

let __env = GameGlobal.wx || GameGlobal.tt || GameGlobal.swan;
let sharedCanvas = __env.getSharedCanvas();
let sharedContext = sharedCanvas.getContext('2d');



function updateViewPort(data) {
    Layout.updateViewPort({
        x: data.x,
        y: data.y,
        width: data.width,
        height: data.height,
    });
}

function showFriendList() {
    return new Promise(function(resolve, reject) {
        let dataDemo = {
            data: [],
        };
        wx.getFriendCloudStorage({
            keyList: ['score'],
            success: function(res) {
                console.log('--success friends res:', res);
                dataDemo.data = []
                if (res.data != null && res.data.length > 0) {
                    for (let j = 0; j < res.data.length; j++) {

                        let item = {};
                        item.avatarUrl = res.data[j].avatarUrl
                        item.nickname = res.data[j].nickname
                        item.openid = res.data[j].openid
                        dataDemo.data.push(item);

                    }
                }
                resolve(dataDemo)
            },
            fail: function(res) {
                console.log('--fail friends res:', res);
                resolve(dataDemo)
            },
            complete: function(res) {
                console.log('--complete friends res:', res);
            },
        })
    })
}

function getTemplate(it, type) {
    var out = '<view class="container"> <scrollview class="array"> ';
    var arr1 = it.data;
    if (arr1) {
        var item, index = -1,
            l1 = arr1.length - 1;
        while (index < l1) {
            item = arr1[index += 1];
            out += ' ';
            if (index % 2 === 1) { out += ' <view class="listItem"> '; }
            out += ' ';
            if (index % 2 === 0) { out += ' <view class="listItem listItemOld"> '; }
            out += ' <view id="listItemUserData"> <text class="listItemNum" value="' + (index + 1) + '"></text> <image class="listHeadImg" src="' + (item.avatarUrl) + '"></image> <text class="listItemName" value="' + '测试账号' //(item.nickname)
                +
                '"></text> </view>'
            if (type == 'give') {
                out += ' <text class="listItemButton" value="赠送精力"></text></view> ';
            } else {
                out += ' <text class="listItemButton" value="索要精力"></text></view> ';
            }

        }
    }
    out += ' </scrollview></view>';
    return out
}

__env.onMessage(data => {
    console.info('data:', data)
    if (data.event === 'viewport') {
        updateViewPort(data)
    }

    if (data.type === 'give') {
        showFriendList().then(res => {
            let dataDemo = res
            let template = getTemplate(dataDemo, data.type)

            Layout.clear();
            Layout.init(template, style);
            Layout.layout(sharedContext);

            let button = Layout.getElementsByClassName('listItem')
            console.info('button:', button)
            if (button.length > 0) {
                for (let i = 0; i < button.length; i++) {
                    console.info(button[i])
                    button[i].on('click', (e) => {
                        console.info('e:', e)
                        let text = button[i].children[1].value
                        let buttonTxt = '赠送精力'
                        let resButtonTxt = '已赠送'
                        let key = '1'
                        let title = '送你 5 个精力，赶快打开游戏看看吧'
                        console.info('data.value:', data.value)
                        if (text !== resButtonTxt) {
                            let openId = dataDemo.data[i].openid
                            console.info('openId:', openId)
                            console.info(button[i])
                            console.info(button[i].children[0].children[0].value)
                            Layout.repaint()
                            wx.modifyFriendInteractiveStorage({
                                key: key,
                                opNum: 1,
                                operation: 'add',
                                toUser: openId, // 好友的 openId
                                title: title, // 2.9.0 支持
                                success: (res) => {
                                    button[i].children[1].value = resButtonTxt
                                        // 后台验证通过
                                        // this.globalVar.giftCountRemaining--
                                        //     this.drawGiftCountRemaining()
                                    console.info('后台验证通过')
                                },
                                fail: (err) => {
                                    // 后台验证不通过
                                    // other code ...
                                    console.info('后台验证失败')
                                    console.info(err)
                                }
                            })
                        }
                    })
                }
            }
            console.info('success')
        })
    }
});